/**
 * Cesium3DTile数据模型
 * */
import LayerModel from '../LayerModel';
import store from '@/store/store';

export default class Cesium3DTileLayerModel extends LayerModel {

  constructor(layerInfo){
    super(layerInfo);
  }

  addLayer(){

    let url = this.layerInfo.url;
    let show = this.layerInfo.show || false;

    // 判断服务是否已经加载
    if(store.state.viewerLayers[url]) {
      console.error(`Cesium3DTileLayerModel添加图层错误，原因：该图层已经存在。url = ${url}。`);
    }

    let tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
      url: url,
      show: show
    }));

    tileset.readyPromise.then(() => {

      // 保存当前图层对象到模型
      this.childLayer = tileset;

      // 将对象添加到图层列表中
      store.state.viewerLayers[url] = this;

    }).otherwise(errInfo => {
      console.error(`Cesium3DTileLayerModel添加图层错误，url = ${url}。原因：${errInfo}。`);
    });
  }

  flyTo(){

    // 经纬度坐标定位
    let isFly = super.flyTo(); // 调用父类的飞行方法：经纬度坐标定位、笛卡三维笛卡尔坐标定位

    // 没有在配置文件中定义坐标位置坐标
    if(!isFly) {

      let tileset = this.childLayer;
      if(!!tileset) {

        let boundingSphere = tileset.boundingSphere;
        viewer.camera.viewBoundingSphere(boundingSphere, new Cesium.HeadingPitchRange(0.0, -0.5, boundingSphere.radius));
        // viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); // 绑定视角
      }
    }
  }

  // 设置图层的可见性
  setVisible(isVisible){

    let tileset = this.childLayer;
    if(tileset) {
      tileset.show = isVisible;
    }
  }


  // 删除图层
  removeLayer(){

    let tileset = this.childLayer;
    if(tileset) {
      let isSuccess = scene.primitives.remove(tileset);
      if(isSuccess){
        let url = this.layerInfo.url;
        if(store.state.viewerLayers[url]) {
          store.state.viewerLayers[url] = undefined;
          delete store.state.viewerLayers[url];

          return true;
        }
      }
    }
  }

}

